import React, { memo, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import Scroll, { PropTypes } from "../../components/scroll/scroll";
import { globalStyle } from "../../assets/global-style";

const List = styled.div`
    display: flex;
    align-items: center;
    height: 30px;
    overflow: hidden;

    >span:first-of-type {
        display: block;
        flex: 0 0 auto;
        padding: 5px 0;
        margin-right: 5px;
        color: gray;
        font-size: ${globalStyle["font-size-m"]};
    }
`;

const ListItem = styled.span`
    flex: 0 0 auto;
    font-size: ${globalStyle["font-size-m"]};
    padding: 5px 8px;
    border-radius: 10px;
    &.selected {
        color: ${globalStyle["color-red"]};
        border: 1px solid ${globalStyle["color-red"]};
        opacity: 0.8;
    }
`;

interface Props extends csc.Props {
    list?: any[];              // 接收的列表数据
    oldVal?: string;        // 当前的 item 值
    title?: string;         // 为列表左边的标题
    handleClick: Function  // 点击不同的 item 执行的方法
}

const Horizen: React.FC<Props> = (props) => {
    const { list, oldVal, title } = props;
    const { handleClick } = props;

    // 加入声明
    const Category: any = useRef(null);

    // 加入初始化内容宽度的逻辑
    useEffect(() => {
        // let categoryDOM: HTMLElement = Category.current;
        // let tagElems = categoryDOM.querySelectorAll("span");
        // let totalWidth = 0;

        // Array.from(tagElems).forEach(ele => {
        //     totalWidth += ele.offsetWidth;
        // });

        // categoryDOM.style.width = `${totalWidth}px`;
    }, []);

    return (
        <Scroll direction="horizental" >
            <div ref={Category} >
                <List>
                    <span>{ title }</span>
                    {
                        list?.map((item: any) => {
                            return (
                                <ListItem onClick={() => handleClick(item.key)} key={item.key} className={`${oldVal === item.key ? 'selected' : '' }`} >
                                    {item.name}
                                </ListItem>
                            )
                        })
                    }
                </List>
            </div>
        </Scroll>
    );
}

export default memo(Horizen);

Horizen.defaultProps = {
    list: [],
    oldVal: '',
    title: '',
    handleClick: () => {}
}
